/**
 * Created by acer on 2015/3/19.
 */
var appSocket='';

var overDelete=0

//获取url内？后内容
var request ={
    QueryString : function(val){
        var uri = window.location.search;
        var re = new RegExp("" +val+ "=([^&?]*)", "ig");
        return ((uri.match(re))?decodeURIComponent(uri.match(re)[0].substr(val.length+1)):null);
    }
}

var loginUserName=request.QueryString('username')

var commmonUrlArray={
    findOrderByConditionsUrl:'/order/findOrderByConditions',//按条件查询结果列表
    updateOrderUrl:'/order/updateOrder',//修改订单
    exWareHouseUrl:'/order/exWareHouse',//出库接口
    inWareHouseUrl:'/order/inWareHouse',//入库接口
    upload:'/file/upload',//上传文件接口
    findOrderInfoByOrderIDUrl:'/order/findOrderInfoByOrderID?',//根据唯一标识id获取详情
    deleteOrderUrl:'/order/deleteOrder?',//根据唯一标识id获取详情
    deleteOrderByBatchIDUrl:'/order/deleteOrderByBatchID?',//根据excelID删除整份
    doubleCheckedUrl:'/order/doubleChecked?batchID='//根据excelID获取整份
}

function getAjax(url,params,callback){
    var param ={
        url:appSocket+url+decodeURIComponent($.param(params)).replace(/'/,''),
        method:'get'
    }
    ajaxRequest(param,callback)
}

function postAjax(url,data,callback){
    var param ={
        url:appSocket+url,
        data:data,
        method:'post'
    }
    ajaxRequest(param,callback)
}
var userInfo;

$(document).ready(function(){

    //if(loginUserName){
    //    userInfo=json_decode(cookie.get('userInfo'+loginUserName))
    //    if(userInfo==null||userInfo==''||userInfo==undefined){
    //        alert('请先登陆！')
    //        location.href='../loginIndex.html'
    //    }
    //    $('#page-wrapper nav:eq(0) li:eq(0)').bind('click',function(){
    //        if(confirm('是否退出登录？')){
    //            cookie.remove('userInfo'+loginUserName)
    //            location.href='../loginIndex.html'
    //        }
    //    })
    //    $('#side-menu li:not(".nav-header")').each(function(){
    //        var self=this
    //        if($(self).find('a').attr('href')==''||$(self).find('a').attr('href')=='#'){
    //        }
    //        else{
    //            $(self).find('a').attr('href',$(self).find('a').attr('href')+'?username='+loginUserName)
    //        }
    //    })
    //}
    //else{
    //    $('#page-wrapper nav:eq(0) li:eq(0)').bind('click',function(){
    //        cookie.remove('userInfo'+loginUserName)
    //        location.href='../loginIndex.html'
    //    })
    //}
    try{
        /*$('.timeAccurate').datetimepicker({
            minView:'0',
            format: 'yyyy-mm-dd hh:ii:ss',
            pickTime: false,
            autoclose:true,
            language:"zh-CN",
            todayBtn:  1
        });*/
            $('.timeAccurate').datepicker( {
                format: 'yyyy-mm-dd',
                pickTime: false,
                autoclose: true,
                todayHighlight: true,
                language:"cn"
                //endDate: "today"
                //startDate: "today"
            } );
    }
    catch(err){
        console.log('无需时间控件')
    }
    $('*').find('a:contains("新 增")').bind('click',function(){
        var btnHtml=$(this).parents().html()
        btnHtml=btnHtml.substring(btnHtml.indexOf('data-target='),btnHtml.indexOf(' onclick="clean()"',btnHtml.indexOf('data-target=')))
        var btnHtmlArray=btnHtml.split('=')
        $(btnHtmlArray[1].replace(/"/g,"")).on('shown.bs.modal',function(e){
            setTimeout(function(){
                $(e.currentTarget).find('input:eq(0)').focus()
            },500)
        })
    })

})

//function ajaxRequest(params,CallBack){
//    params=JSON.parse(params)
//    //try{
//    //    params.data['userId']=userInfo._id
//    //}
//    //catch(err){
//    //alert('请重新登录')
//    //    location.href='../loginIndex.html'
//    //}
//    alert(params.url)
//    $.ajax({
//        url:params.url,
//        contentType: "application/json",
//        data:JSON.stringify(params.data),
//        "Content-Type":"utf-8",
//        type:params.method,
//        async:true,
//        dataType:"json",
//        success:CallBack,
//        timeout:30*1000,
//        error:function(err){
//            //alert(JSON.stringify(err));
//            if(err.statusText=='timeout') {
//                alert("请求超时，请刷新页面");
//                this.abort();
//            }
//        }
//    });
//    function reStoreCookie(data){
//        if(data.data.loginStatus==false){
//            location.href='../loginIndex.html'
//        }
//        else{
//            var name='userInfo'+loginUserName
//            var cval=cookie.get(name);
//            if(cval!=null)
//                cookie.set(name,cval)
//            CallBack(data)
//        }
//    }
//}

////跨域ajax
function ajaxRequest(params,CallBack){
//    alert(params)
    //try{
    //    params.data['userId']=userInfo._id
    //}
    //catch(err){
    //alert('请重新登录')
    //    location.href='../loginIndex.html'
    //}
//    ats(params)
//    params=JSON.parse(params)
    $.ajax({
        url:params.url,
        data:params.data,
        type:params.method,
        //async:false,
        dataType:"json",
        success:function(data){
            ats(data)
            CallBack(data)
        },
        timeout:30*100000,
        error:function(err){
            //alert(JSON.stringify(err));
            if(err.statusText=='timeout') {
                alert("请求超时，请刷新页面");
                this.abort();
            }
        }
    });
}

//分页处理
function paging(listdata){
    $('.wrapper-content').css('visibility','visible')
    var topage=toPage;
    /*分页判断start*/
    pagesnum=listdata;/*总页数*/
    var pages = [];
    if(topage>=3&&(pagesnum-topage)>=3){
        var str=[];
        var spage = topage-3;
        for(var i=1;i<=5;i++){
            str[i-1]={page:spage+i}
        }
        pages = {currentpage:topage,pages:str};
        return pages;
    }else if(topage<3&&(pagesnum-topage)<3){
        var str=[];
        for(var i=1;i<=pagesnum;i++){
            str[i-1]={page:i}
        }
        pages = {currentpage:topage,pages:str};
        return pages;
    }else if(topage>=3&&(pagesnum-topage)<3){
        if(topage<=4){
            var str=[];
            for(var i=1;i<=pagesnum;i++){
                str[i-1]={page:i}
            }
            pages = {currentpage:topage,pages:str};
        }else{
            var str=[];
            var spage = pagesnum-5;
            for(var i=1;i<=5;i++){
                str[i-1]={page:spage+i}
            }
            pages = {currentpage:topage,pages:str};
        }
        return pages;
    }else if(topage<3&&(pagesnum-topage)>=3){
        var str=[];
        var j;
        if(pagesnum<=5){
            j=pagesnum;
        }else{
            j=5;
        }
        for(var i=1;i<=j;i++){
            str[i-1]={page:i}
        }
        pages = {currentpage:topage,pages:str};
    }
    return pages;
    /*分页判断end*/
}




//获取当前时间
getNow = function(){
    var time=new Date()
    var year=time.getFullYear()
    var month=time.getMonth()+1
    if(month<10){
        month='0'+month
    }
    var day=time.getDate()
    var hour=time.getHours()
    var minute=time.getMinutes()
    var second=time.getSeconds()
    var now=year+"-"+month+"-"+day+" "+hour+":"+minute+':'+second
    return now
}

Date.prototype.Format = function(fmt){
    var o = {
        "M+" : this.getMonth()+1,                 //月份
        "d+" : this.getDate(),                    //日
        "h+" : this.getHours(),                   //小时
        "m+" : this.getMinutes(),                 //分
        "s+" : this.getSeconds(),                 //秒
        "q+" : Math.floor((this.getMonth()+3)/3), //季度
        "S"  : this.getMilliseconds()             //毫秒
    };
    if(/(y+)/.test(fmt))
        fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));
    for(var k in o)
        if(new RegExp("("+ k +")").test(fmt))
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
    return fmt;
};

//转JSON格式的alert
function ats(l){
    //alert(JSON.stringify(l))
}

//元素内判断input:text是否为空
function alertEmpty(modalName){
    var judge=0
    $(modalName+" input:text[name='alertEmpty']").each(function(){
            if($(this).val()==""){
                var emptyName=$(this).parents().prev('label').text().replace(/：/,'')
                alert(emptyName+"不能为空");
                judge=1
            }
        }
    );
    if(judge==0){
        return true
    }
}

//手机格式验证，类似于confirm
function phoneFormTest(phone){
    //var reg=/^(1[345][0-9]{9})$/
    var reg=/(^[0-9]{3,4}\-[0-9]{7,8}$)|(^[0-9]{7,8}$)|(^\([0-9]{3,4}\)[0-9]{3,8}$)|(^0{0,1}13[0-9]{9}$)|(13\d{9}$)|(15[0135-9]\d{8}$)|(18[267]\d{8}$)|(^[0-9]{3,4}\-[0-9]{3,4}\-[0-9]{3,4}$)/
    if(reg.test(phone)){
     return true;
 }
    else {
     return false;
 }
}

//邮箱格式验证，类似于confirm
function emailFormTest(email){
    var reg = /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/;
    if(reg.test(email)){
        return true;
    }
    else {
        return false;
    }
}

/***cookie内JSON转化为数组**/
function json_decode(str_json) {
    // Decodes the JSON representation into a PHP value
    //
    // version: 906.1806
    // discuss at: http://phpjs.org/functions/json_decode
    // +      original by: Public Domain (http://www.json.org/json2.js)
    // + reimplemented by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // + improved by: T.J. Leahy
    // *     example 1: json_decode('[\n    "e",\n    {\n    "pluribus": "unum"\n}\n]');
    // *     returns 1: ['e', {pluribus: 'unum'}]
    /*
     http://www.JSON.org/json2.js
     2008-11-19
     Public Domain.
     NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
     See http://www.JSON.org/js.html
     */

    var json = this.window.JSON;
    if (typeof json === 'object' && typeof json.parse === 'function') {
        return json.parse(str_json);
    }

    var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;
    var j;
    var text = str_json;

    // Parsing happens in four stages. In the first stage, we replace certain
    // Unicode characters with escape sequences. JavaScript handles many characters
    // incorrectly, either silently deleting them, or treating them as line endings.
    cx.lastIndex = 0;
    if (cx.test(text)) {
        text = text.replace(cx, function (a) {
            return '\\u' +
                ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
        });
    }

    // In the second stage, we run the text against regular expressions that look
    // for non-JSON patterns. We are especially concerned with '()' and 'new'
    // because they can cause invocation, and '=' because it can cause mutation.
    // But just to be safe, we want to reject all unexpected forms.

    // We split the second stage into 4 regexp operations in order to work around
    // crippling inefficiencies in IE's and Safari's regexp engines. First we
    // replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
    // replace all simple value tokens with ']' characters. Third, we delete all
    // open brackets that follow a colon or comma or that begin the text. Finally,
    // we look to see that the remaining characters are only whitespace or ']' or
    // ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.
    if (/^[\],:{}\s]*$/.
            test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@').
                replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
                replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {

        // In the third stage we use the eval function to compile the text into a
        // JavaScript structure. The '{' operator is subject to a syntactic ambiguity
        // in JavaScript: it can begin a block or an object literal. We wrap the text
        // in parens to eliminate the ambiguity.

        j = eval('(' + text + ')');

        return j;
    }

    // If the text is not JSON parseable, then a SyntaxError is thrown.
    throw new SyntaxError('json_decode');
}

/***cookie内数组转化为JSON**/
function json_encode(mixed_val) {
    // Returns the JSON representation of a value
    //
    // version: 906.1806
    // discuss at: http://phpjs.org/functions/json_encode
    // +      original by: Public Domain (http://www.json.org/json2.js)
    // + reimplemented by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // + improved by: T.J. Leahy
    // *     example 1: json_encode(['e', {pluribus: 'unum'}]);
    // *     returns 1: '[\n    "e",\n    {\n    "pluribus": "unum"\n}\n]'
    /*
     http://www.JSON.org/json2.js
     2008-11-19
     Public Domain.
     NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
     See http://www.JSON.org/js.html
     */
    var json = this.window.JSON;
    if (typeof json === 'object' && typeof json.stringify === 'function') {
        return json.stringify(mixed_val);
    }

    var value = mixed_val;

    var quote = function (string) {
        var escapable = /[\\\"\u0000-\u001f\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;
        var meta = {    // table of character substitutions
            '\b': '\\b',
            '\t': '\\t',
            '\n': '\\n',
            '\f': '\\f',
            '\r': '\\r',
            '"' : '\\"',
            '\\': '\\\\'
        };

        escapable.lastIndex = 0;
        return escapable.test(string) ?
        '"' + string.replace(escapable, function (a) {
            var c = meta[a];
            return typeof c === 'string' ? c :
            '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
        }) + '"' :
        '"' + string + '"';
    };

    var str = function(key, holder) {
        var gap = '';
        var indent = '    ';
        var i = 0;          // The loop counter.
        var k = '';          // The member key.
        var v = '';          // The member value.
        var length = 0;
        var mind = gap;
        var partial = [];
        var value = holder[key];

        // If the value has a toJSON method, call it to obtain a replacement value.
        if (value && typeof value === 'object' &&
            typeof value.toJSON === 'function') {
            value = value.toJSON(key);
        }

        // What happens next depends on the value's type.
        switch (typeof value) {
            case 'string':
                return quote(value);

            case 'number':
                // JSON numbers must be finite. Encode non-finite numbers as null.
                return isFinite(value) ? String(value) : 'null';

            case 'boolean':
            case 'null':
                // If the value is a boolean or null, convert it to a string. Note:
                // typeof null does not produce 'null'. The case is included here in
                // the remote chance that this gets fixed someday.

                return String(value);

            case 'object':
                // If the type is 'object', we might be dealing with an object or an array or
                // null.
                // Due to a specification blunder in ECMAScript, typeof null is 'object',
                // so watch out for that case.
                if (!value) {
                    return 'null';
                }

                // Make an array to hold the partial results of stringifying this object value.
                gap += indent;
                partial = [];

                // Is the value an array?
                if (Object.prototype.toString.apply(value) === '[object Array]') {
                    // The value is an array. Stringify every element. Use null as a placeholder
                    // for non-JSON values.

                    length = value.length;
                    for (i = 0; i < length; i += 1) {
                        partial[i] = str(i, value) || 'null';
                    }

                    // Join all of the elements together, separated with commas, and wrap them in
                    // brackets.
                    v = partial.length === 0 ? '[]' :
                        gap ? '[\n' + gap +
                        partial.join(',\n' + gap) + '\n' +
                        mind + ']' :
                        '[' + partial.join(',') + ']';
                    gap = mind;
                    return v;
                }

                // Iterate through all of the keys in the object.
                for (k in value) {
                    if (Object.hasOwnProperty.call(value, k)) {
                        v = str(k, value);
                        if (v) {
                            partial.push(quote(k) + (gap ? ': ' : ':') + v);
                        }
                    }
                }

                // Join all of the member texts together, separated with commas,
                // and wrap them in braces.
                v = partial.length === 0 ? '{}' :
                    gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' +
                    mind + '}' : '{' + partial.join(',') + '}';
                gap = mind;
                return v;
        }
    };

    // Make a fake root object containing our value under the key of ''.
    // Return the result of stringifying the value.
    return str('', {
        '': value
    });
}

//cookie的增、删、查
var cookie = {
    set:function(name,value){
        var exp = new Date();
        exp.setTime(exp.getTime() + 6*60*60*1000);
        document.cookie=name+"="+escape(value)+";expires="+exp.toGMTString()+';path=/backEndAll/'
    },
    get:function(name){
        var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
        if(arr=document.cookie.match(reg))
            return unescape(arr[2]);
        else
            return null;
    },
    remove:function(name){
        var exp = new Date();
        exp.setTime(exp.getTime() - 1);
        var cval=cookie.get(name);
        if(cval!=null)
            document.cookie= name + "="+cval+";expires="+exp.toGMTString()+';path=/backEndAll/';
    }
}

//监听键盘事件
function addListeningKeyDown(where,whichKey,whereClick){
    if($(where).focus()){
        $(where).on('keydown',function(){
            if(event.keyCode==whichKey){
                $(whereClick).trigger('click')
            }
        })
    }
}

function resetCreateNoticeModal(){
}

//判断value是否为空
function isNull(arg1)
{
    return !arg1 && arg1!==0 && typeof arg1!=="boolean"?true:false;
}
